<?php

/**
 * Created by PhpStorm.
 * User: shadow
 * Date: 2017/3/6
 * Time: 15:32
 */

namespace Utils\Service\Tencent;

use Utils\Service\Common\Curl;

/**
 * 腾讯短信库
 * Class TencentSmsService
 * @package App\Service\Core
 */
trait Sms
{
    use Curl;
    protected $uri;
    protected $app_id;
    protected $app_secret_key;
    protected $sign;
    protected $mobile;
    protected $type = 0;
    protected $random;
    protected $nation_code;
    protected $msg;
    protected $time;

    /**
     * init tencent sms ,it to do set key of appid and secre
     */
    public function initSms($appID, $appSercretKey, $url)
    {
        $this->app_id = $appID;
        $this->app_secret_key = $appSercretKey;
        $this->uri = $url;
    }

    /**set signature for check
     * @return $this
     */
    protected function setSign()
    {
        $this->sign = md5($this->app_secret_key . $this->mobile);

        return $this;
    }

    protected function setNationCode($code = '86')
    {
        $this->nation_code = $code;
        return $this;

    }

    protected function setTime()
    {
        $this->time = time();
        return $this;

    }

    protected function setMobile($mobile)
    {
        $this->mobile = $mobile;
        return $this;


    }

    protected function setMsg($msg)
    {
        $this->msg = $msg;
        return $this;
    }


    public function getUri()
    {
        return sprintf('%s?sdkappid=%s', $this->uri, $this->app_id);
    }

    protected function getPostData()
    {
        $data["tel"] = array(
            "nationcode" => $this->nation_code,
            "mobile" => $this->mobile
        );
        $data["type"] = $this->type;
        $data["msg"] = $this->msg;
        $data["sig"] = $this->sign;
        $data["time"] = $this->time;
        $data["extend"] = "";
        return json_encode($data);
    }


    function getRandom()
    {
        return rand(100000, 999999);
    }

    function calculateSig($appkey, $random, $curTime, $phoneNumbers)
    {
        $this->sign = hash("sha256", "appkey=" . $appkey . "&random=" . $random . "&time=" . $curTime . "&mobile=" . $phoneNumbers);
    }


    public function sendToSms($mobile, $msg)
    {
        $random = $this->getRandom();
        $this->setMobile($mobile)->setTime()->setNationCode()->setMsg($msg)->calculateSig($this->app_secret_key, $random, $this->time, $mobile);
        return $this->curlPost($this->getUri() . '&random=' . $random, $this->getPostData());
    }

}